<template>
    <div class="container">
        <!-- 添加按钮区 -->
        <div class="btn_zone">
            <el-row style="align-items: center; text-align: center;">
                <el-col :span="1"><el-button type="primary" @click="handleAddTeacher">添加老师</el-button></el-col>
                <el-col :span="1" :push="22"><el-icon><ArrowUpBold /></el-icon></el-col>
            </el-row>
        </div>
        <el-divider />
        <!-- 表格区 -->
        <div class="tbl_zone">
            
            <el-table :data="tableData" :default-sort="{prop: 'seq', order: 'ascending'}" style="width: 100%;" size="large">
                <el-table-column fixed prop="id" label="#" sortable width="80" />
                <el-table-column fixed prop="employeeName" label="老师名" sortable width="150" />
                <el-table-column prop="employeeSex" label="性别" width="100" />
                <el-table-column prop="employeePhone" label="手机号码" sortable width="200" />
                <el-table-column prop="employeeNote" label="备注" width="480" />
                <el-table-column fixed="right" label="操作" min-width="120">
                  <template #default="scope">
                    <el-button link type="primary" @click="handleDetail(scope.row.id)">
                      查看详情&nbsp;<el-icon><InfoFilled /></el-icon>
                    </el-button>
                    <el-button link type="success" @click="handleEdit(scope.row.id)">Edit&nbsp;<el-icon><Edit /></el-icon></el-button>
                    <el-button link type="danger"  @click="handleDelete(scope.row.id)">删除&nbsp;<el-icon><Delete /></el-icon></el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页区域 -->
              <!-- <div class="pagination-container">
                <el-pagination background layout="prev, pager, next" :total="total"/>
              </div> -->
                <el-row>
                  <el-col :span="20">
                    <el-pagination  v-model:current-page="pageData.pageCurrent"
                                    :page-size="pageData.pageSize"
                                    layout="prev, pager, next"
                                    :total="pageData.pageTotal"
                                    prev-text="上一页"
                                    next-text="下一页"
                                    @current-change="handleCurrentChange" />
                  </el-col>
                  <el-col :span="4" style="font-size: 14px;">
                    <span>当前 {{(pageData.pageCurrent-1)*pageData.pageSize+1}} 条到 {{ pageData.pageSize*pageData.pageCurrent }} 条 共 {{pageData.pageTotal}} 条</span>  </el-col>
                </el-row>
        </div>


        <!-- 抽屉区 -->
        <el-drawer
        v-model="drawer"
        direction="rtl"
        size="50%">
            <!-- 自定义头部 --> 
            <template #header="{ titleId, titleClass }">
                <h2 :id="titleId" :class="titleClass">{{ drawerTitle }}</h2>
            </template>
            <!-- 添加表单 -->
            <el-form
                ref="teacherFormRef"
                style="max-width: 600px"
                :model="teacherForm"
                :rules="rules"
                label-width="auto"
                class="add_teacher_form"
                status-icon>
                <el-form-item label="老师姓名" prop="name">
                    <el-input v-model="teacherForm.name" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="teacherForm.phone" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="teacherForm.email" />
                </el-form-item>
            
                <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="teacherForm.sex">
                        <el-radio value="男">男</el-radio>
                        <el-radio value="女">女</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="出生日期" prop="birth">
                    <el-date-picker v-model="teacherForm.birth"
                            type="date"
                            aria-label="Pick a date"
                            placeholder="选择日期"
                            style="width: 100%"/>
                </el-form-item>

                <el-form-item label="老师介绍" prop="introduce">
                    <el-input v-model="teacherForm.introduce" type="textarea" />
                </el-form-item>

                <el-form-item>
                  <el-button v-if="drawerTitle === '添加老师'" type="primary" @click="submitForm(teacherFormRef)">
      添加
    </el-button>
    <el-button v-if="drawerTitle === '修改老师'" type="success" @click="changeForm(teacherFormRef, currentRowId)">
      修改
    </el-button>
                    <el-button @click="resetForm(teacherFormRef)">重置</el-button>
                </el-form-item>

            </el-form>

        </el-drawer>

    </div>

</template>

<script setup>
import loadJson from '@/requests/loadJson.js' 
import  { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'

// //定义响应式对象
// const tableData = ref(null)
// const total = ref(1)

// //定义异步方法来加载数据
// async function fetchLocalData() {
//     try {
//         const data = await loadJson('demoDatas/teacher/tableData.json')
//         tableData.value = data
//         //获取数组的长度
//         total.value = data.length
//     } catch (error) {
//         console.error('从loadJson.js调用时发生错误:', error)
//     }
// }
// //调用方法
// onMounted(()=> {
//     console.log('页面挂载完成，加入本地json文件');
//     //todo 这里需要开发人员修改，改成加载后端的数据
//     fetchLocalData()
// }) 





import axios from 'axios' // 确保已经安装了axios并导入

// 定义响应式对象
const tableData = ref(null)
const total = ref(1)
const pageData = reactive({
  pageCurrent:1,
  pageSize:10,
  pageTotal:50
})
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  pageData.pageCurrent = val
  fetchRemoteData();
}
const baseUrl = import.meta.env.VITE_APP_BASE_URL; // 使用 import.meta.env 读取环境变量
// 定义异步方法来加载数据
async function fetchRemoteData() {
    try {
        const response = await axios.get(`${baseUrl}/employee/list`, { // 发送GET请求到后端API
      params: {
        page: pageData.pageCurrent,
        size: pageData.pageSize
      }
    })
        
        if (response.data.code === 200 && response.data.message === 'success') {
            tableData.value = response.data.data
            // 获取数组的长度
            total.value = tableData.value.length
        } else {
            console.error('服务器返回了错误的状态码或消息:', response.data)
        }
    } catch (error) {
        console.error('从远程API调用时发生错误:', error)
    }
}

// 调用方法
onMounted(() => {
    console.log('页面挂载完成，开始加载后端数据');
    fetchRemoteData()
})







const drawer = ref(false)
const drawerTitle = ref('添加老师')

// 给添加按钮添加事件处理，弹出抽屉
const handleAddTeacher = () => {
    drawer.value = true
    drawerTitle.value = '添加老师'
}

// 以下是在抽屉里的按钮添加的事件和表单验证相关的操作
const teacherFormRef = ref()
const teacherForm = reactive({
    name: '',
    phone: '',
    email: '',
    sex: '',
    birth: '',
    introduce: '',
})
// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入老师姓名', trigger: 'blur' },
    { min: 3, max: 10, message: '姓名长度在3-10之间', trigger: 'blur' },
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号码',
      trigger: 'blur',
    },
  ],
  sex: [
    {
        required: true,
        message: '请选择性别',
        trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur',
    },
  ],
  birth: [
    {
      type: 'date',
      required: true,
      message: '请选择生日',
      trigger: 'change',
    },
  ],
  introduce: [
    { required: false, message: '自我介绍', trigger: 'blur' },
  ],
})

// 提交和重置函数
const submitForm = async (formElement) => {
    if (!formElement) return
    // 进行验证
    await formElement.validate(async (valid, fields) => {
        if (valid) {
            console.log('submit!')

            // 将表单数据转换为EmployeeDto格式
            const employeeDto = {
                employeeName: teacherForm.name,
                employeePhone: teacherForm.phone,
                employeeSex: teacherForm.sex,
                employeeBirthday: teacherForm.birth, // 假设birth已经是Date类型
                employeeIntroduction: teacherForm.introduce,
                // 其他字段默认值或空字符串
                employeeAvatarUrl: '',
                employeeNote: '',
                employeeRoleName: '',
                employeeRolePassword: '',
                employeeRoleType: 0,
                employeeRoleEmail: teacherForm.email,
                employeeIsDeleted: 0,
                employeeCreateTime: new Date().toDateString,
                employeeLastModifyTime: new Date().toDateString,
                employeeVersion: 0,
            }

            // 发送POST请求到后端
            try {
                const response = await axios.post(`${baseUrl}/employee/save`, employeeDto);

                if (response.data.code === 200) {
                    ElMessage({
                        message: '添加成功',
                        type: 'success'
                    });
                    drawer.value = false; // 关闭抽屉
                    // 刷新表格数据
                    fetchRemoteData(); // 假设fetchRemoteData是获取数据的方法
                } else {
                    ElMessage({
                        message: '添加失败: ' + response.data.message,
                        type: 'error'
                    });
                }
            } catch (error) {
                ElMessage({
                    message: '添加失败: ' + error.message,
                    type: 'error'
                });
                console.error('添加失败', error);
            }
        } else {
            console.log('表单验证失败，请重新填写', fields)
        }
    })
}


// const drawer = ref(false)
// const drawerTitle = ref('添加老师')

// //给添加按钮添加事件处理，弹出抽屉
// const handleAddTeacher = () => {
//     drawer.value = true
//     drawerTitle.value = '添加老师'
// }

// //以下是在抽屉里的按钮添加的事件和表单验证相关的操作
// const teacherFormRef = ref()
// const teacherForm = reactive({
//     name: '',
//     phone: '',
//     email: '',
//     sex: '',
//     birth: '',
//     introduce: '',
// })
// //表单验证规则
// const rules = reactive({
//   name: [
//     { required: true, message: '请输入老师姓名', trigger: 'blur' },
//     { min: 3, max: 6, message: '姓名长度在3-6之间', trigger: 'blur' },
//   ],
//   phone: [
//     {
//       required: true,
//       message: '请输入手机号码',
//       trigger: 'blur',
//     },
//   ],
//   sex: [
//     {
//         required: true,
//         message: '请选择性别',
//         trigger: 'blur'
//     }
//   ],
//   email: [
//     {
//       required: true,
//       message: '请输入邮箱',
//       trigger: 'blur',
//     },
//   ],
//   birth: [
//     {
//       type: 'date',
//       required: true,
//       message: '请选择生日',
//       trigger: 'change',
//     },
//   ],
//   introduce: [
//     { required: false, message: '自我介绍', trigger: 'blur' },
//   ],
// })

// //提交和重置函数
// const submitForm = async (formElement) => {
//     console.log(formElement)

//     if (!formElement) return
//     //进行验证
//     await formElement.validate((valid, fields) => {
//         if (valid) {
//             console.log('submit!')
//             // todo 这里去提交表单数据到后端
//             // ...

//         } else {
//             console.log('表单验证失败，请重新填写', fields)
//         }
//     })
// }
//重置表单，这里不传参数也可以，因为我们定义了 teacherFormRef 对象
const resetForm = (formElement) => {
    if (!formElement) return
    formElement.resetFields()
}

//useRouter钩子则用来访问路由器实例本身。它返回一个路由器对象，让你能够进行导航（比如push、replace）、
//获取路由器的全局状态或添加路由守卫等功能。
const router = useRouter()

//------- 以下三个方法是处理表格中的三个按钮的，需要自行完成代码
const handleDetail = (id) => {
    //进行编程式导航
    router.push({
        name: 'teacherDetail',
        params: {id: `${id}`}
    }) 
   
}
const currentRowId = ref(null); // 存储当前编辑的行ID
const handleEdit = async (id) =>  {
    //修改抽屉title
    drawerTitle.value = '修改老师'
    //打开抽屉
    drawer.value = true
    currentRowId.value = id;


}
const changeForm = async (formElement, id) => {
  if (!formElement) return;
  await formElement.validate(async (valid, fields) => {
    if (valid) {
      console.log('submit!');

      const employeeDto = {
        id: id,
        employeeName: teacherForm.name,
        employeePhone: teacherForm.phone,
        employeeSex: teacherForm.sex,
        employeeBirthday: teacherForm.birth,
        employeeIntroduction: teacherForm.introduce,
        employeeAvatarUrl: '',
        employeeNote: '',
        employeeRoleName: '',
        employeeRolePassword: '',
        employeeRoleType: 0,
        employeeRoleEmail: teacherForm.email,
        employeeIsDeleted: 0,
        employeeCreateTime: new Date().toISOString(),
        employeeLastModifyTime: new Date().toISOString(),
        employeeVersion: 0,
      };

      try {
        const response = await axios.put(`${baseUrl}/employee/update`, employeeDto);

        if (response.data.code === 200) {
          ElMessage({
            message: '更新成功',
            type: 'success'
          });
          drawer.value = false;
          fetchRemoteData();
        } else {
          ElMessage({
            message: '更新失败: ' + response.data.message,
            type: 'error'
          });
        }
      } catch (error) {
        ElMessage({
          message: '更新失败: ' + error.message,
          type: 'error'
        });
        console.error('更新失败', error);
      }
    } else {
      console.log('表单验证失败，请重新填写', fields);
    }
  });
};


// const handleDelete = () => {
//     ElMessage({
//         message: '你点击了删除老师按钮',
//         type: 'warning'
//     })
//     //todo ...
// }

const handleDelete = async (id) => {
    try {
        const response = await axios.delete(`${baseUrl}/employee/delete/${id}`);
        if (response.data.code === 200) {
            ElMessage({
                message: '删除成功',
                type: 'success'
            });
            // 可能需要刷新表格数据
            fetchRemoteData(); // 假设fetchRemoteData是获取数据的方法
        } else {
            ElMessage({
                message: '删除失败: ' + response.data.message,
                type: 'error'
            });
        }
    } catch (error) {
        ElMessage({
            message: '删除失败: ' + error.message,
            type: 'error'
        });
        console.error('删除失败', error);
    }
};










</script >

<style scoped>
    .pagination-container {
        margin-top: 15px;
        display: flex;
        justify-content: flex-end;
    }

    .add_teacher_form {
        margin: 10px 50px;
    }

</style>